<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button data-path="news">新闻</button>
    <button data-path="play">娱乐</button>
    <button data-path="music">音乐</button>
    <div id="view"></div>
    <script>
      // 路由表单
      const routes = [
        { path: 'news', content: '我是新闻组件' },
        { path: 'play', content: '我是娱乐组件' },
        { path: 'music', content: '我是音乐组件' },
      ];

      // 获取元素
      let btns = document.querySelectorAll('button');
      let view = document.querySelector('#view');

      //步骤：事件改变地址栏-->监听地址栏改变-->视图变化

      btns.forEach((item) => {
        item.onclick = function () {
          // 1改变地址
          console.log(this.dataset.path);
          history.pushState(null, null, this.dataset.path);
          // 2监听地址栏变化
          routes.forEach((item) => {
            if (item.path === this.dataset.path) {
              // 3视图变化
              view.textContent = item.content;
            }
          });
        };
      });

      // 回退功能
      window.onpopstate = function () {
        console.log(location.pathname);
        let oldpath = location.pathname.split('/')[3];
        console.log(oldpath);
        routes.forEach((item) => {
          if (item.path === oldpath) {
            // 3视图变化
            view.textContent = item.content;
          }
        });
      };
    </script>
  </body>
</html>
